package fnic.prehand.common;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFormatService {
	private static Logger LOG = Logger.getLogger(JacksonFormatService.class);
	private static JacksonFormatService instance = new JacksonFormatService();
	ObjectMapper objectMapper ;
    // singleton
	public JacksonFormatService(){
//		objectMapper = new ObjectMapper();
	    objectMapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
	    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	public static JacksonFormatService getInstance() {

		return instance;
	}
	
	/*
	 * 将json String转换为Object
	 * className需要完整的路径
	 */
	public Object String2Obj(String jsonStr, String className){
		Object tempObj = null;
		try {
			tempObj = objectMapper.readValue(jsonStr, Class.forName(className));
		}catch (ClassNotFoundException e) {
			LOG.error("ClassNotFoundException fail: "+ e.getMessage());
		} catch (JsonParseException e) {
			LOG.error("JsonParseException fail: "+e.getMessage());
		} catch (JsonMappingException e) {
			LOG.error("JsonMappingException fail: "+e.getMessage());
		} catch (IOException e) {
			LOG.error("IOException fail: "+e.getMessage());
		}

		return tempObj;
	} 
	
	/*
	 * 将object转换为json String
	 */
	public String Obj2String(Object obj){
		ByteArrayOutputStream strOutStm = null;
		try {
			strOutStm = new ByteArrayOutputStream();
			objectMapper.writeValue(strOutStm, obj);
		} catch (IOException e) {
			System.out.println("json parse obj2string fail: "+e.getMessage());
		}

		return strOutStm.toString();
	}
}
